package com.lxr.test5002;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.Nullable;

import com.lxr.test5002.base.BaseActivity;
import com.lxr.test5002.utils.MyUtil;
import com.sdk.devicemanager.ICcon;
import java.util.Random;

import butterknife.BindView;

/**
 * 类描述:[串口通讯测试]
 * 说明:
 * @author: LXR-zsm
 * @Date: 2023/12/19 17:16
 */
public class PorintTestActivity extends BaseActivity {

    @BindView(R.id.testResult)
     TextView mResult;
    @BindView(R.id.btn_test)
     Button mTestbtn;
    @BindView(R.id.testcount)
     EditText mTestCount;
    private int WRlen = 2048;

    public PorintTestActivity( ) {
        super(R.layout.activity_pointtest);
    }


    @Override
    protected void initView(Bundle savedInstanceState) {

    }

    @Override
    protected void initEvent() {
        mTestbtn.setOnClickListener(view -> {
            //MCU及串口打开
            int state = ICcon.getInstance().mcu_powerAndoPenOrCloseSerialPort(1);
            if (state == 0) {
                ICcon.getInstance().exPowerOn();
                if (ICcon.getInstance().setPCIBandrate(115200)) {
                    Log.e("point_band", "setBand");
                }
                String trim = mTestCount.getText().toString().trim();
                if (trim != null) {
                    int parseInt = Integer.parseInt(trim);
                    successCount = 0;
                    errorCount = 0;
                    testPorint(parseInt);
                    mTestbtn.setEnabled(false);
                    mTestbtn.setAlpha(0.5f);
                }
            } else {
                mResult.setText("上电失败\n通信失败\n下电失败\n测试失败");
            }
        });
    }

    @Override
    protected void initData() {

    }

    private int successCount = 0;
    private int errorCount = 0;
    private int mcount = 0;

    private void testPorint(int count) {
        mcount = count;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (mcount > 0) {
                    String randData = randomHexString(WRlen);
                    Log.e("pointSend", randData);
                    int write = ICcon.getInstance().PCI_CommandWrite(randData.length() / 2, MyUtil.hexToByteArr(randData), 200);
                    Log.e("pointSend", write + "");

                    String string = "";
                    for (int i = 0; i < 2; i++) {
                        byte[] pci_commandRead = ICcon.getInstance().PCI_CommandRead(write/2, 3000, 1);
                        if (pci_commandRead != null) {
                            String s = MyUtil.bytesToString(pci_commandRead).replace(" ", "");
                            Log.e("pointRead"+i, s);
                            string = string + s;
                        }else{
                            Log.e("pointRead"+i, "null");
                        }
                    }
                    Log.e("pointRead2", string);
                    if (randData.equals(string)) {
                        successCount++;
                    } else {
                        errorCount++;
                    }
                    if ((successCount + errorCount) == count) {
                        int state = ICcon.getInstance().mcu_powerAndoPenOrCloseSerialPort(0);
//                        int state = ICcon.oPenOrCloseSerialPort(1,0);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTestbtn.setEnabled(true);
                                mTestbtn.setAlpha(1);
                                if (state == 0) {
//                                    ICcon.exPowerOff();
                                    mResult.append("\n下电成功");
                                } else {
                                    mResult.append("\n下电失败");
                                }
                                if (errorCount > 0) {
                                    mResult.append("\n测试失败\n请检查是否插入板卡！！！");
                                } else {
                                    mResult.append("\n测试成功");
                                }
                                mcount = 0;
                                mTestbtn.setEnabled(true);
                                mTestbtn.setAlpha(1);
                            }
                        });
                    }
                    mResult.setText("上电成功\n" + "测试次数：" + count + "\n数据大小(字节)：1K" + "\n成功次数：" + successCount + "\n失败次数：" + errorCount);
                    mcount--;
                }
            }
        }).start();
    }


    /**
     * 获取16进制随机数
     *
     * @param len
     * @return
     */
    public static String randomHexString(int len) {
        try {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < len; i++) {
                result.append(Integer.toHexString(new Random().nextInt(16)));
            }
            return result.toString().toUpperCase();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onStop() {
        super.onStop();
        mcount = 0;
        int state = ICcon.getInstance().mcu_powerAndoPenOrCloseSerialPort(0);
        ICcon.getInstance().ex3PowerOff();
//        ICcon.oPenOrCloseSerialPort(1,0);
    }
}
